package org.example.redis;

import org.apache.commons.lang3.StringUtils;
import org.springframework.data.redis.cache.RedisCache;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.cache.RedisCacheWriter;

import java.time.Duration;

/**
 * @author: sql
 * @date: 2024/6/7
 * @Description: 通过名字设置过期时间的RedisCacheManager, CacheName=name#过期时间
 * @version: 1.0
 */
public class ExpireRedisCacheManager extends RedisCacheManager {
    public ExpireRedisCacheManager(RedisCacheWriter cacheWriter, RedisCacheConfiguration defaultCacheConfiguration) {
        super(cacheWriter, defaultCacheConfiguration);
    }

    @Override
    protected RedisCache createRedisCache(String name, RedisCacheConfiguration cacheConfig) {
        String[] names = StringUtils.split(name, "#");
        if (names.length != 2) {
            return super.createRedisCache(name, cacheConfig);
        }
        String ttlFromName = names[1];
        int expiredSeconds = Integer.parseInt(ttlFromName);
        return super.createRedisCache(names[0], cacheConfig.entryTtl(Duration.ofSeconds(expiredSeconds)));
    }
}
